package com.lw.leetcode.node;

import java.util.ArrayDeque;
import java.util.Queue;

/**226. 翻转二叉树
 * 剑指 Offer 27. 二叉树的镜像
 * @Author liw
 * @Date 2021/4/16 14:01
 * @Version 1.0
 */
public class InvertTree {

    public static void main(String[] args) {

        TreeNode a = new TreeNode(1);
        TreeNode b = new TreeNode(2);
        TreeNode c = new TreeNode(3);
        TreeNode d = new TreeNode(4);
        TreeNode e = new TreeNode(5);
        a.left = b;
        a.right = c;
        b.right = d;
        c.left = e;
        TreeNode treeNode = new InvertTree().invertTree(a);
        System.out.println(treeNode);
    }

    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            TreeNode left = node.left;
            TreeNode right = node.right;
            node.left = right;
            node.right = left;
            if (left != null) {
                queue.add(left);
            }
            if (right != null) {
                queue.add(right);
            }
        }
        return root;
    }

}
